<!--
  - Copyright (C) 2018-2019
  - All rights reserved, Designed By www.joolun.com
  - 注意：
  - 本软件为www.joolun.com开发研制，未经购买不得使用
  - 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
  - 一经发现盗用、分享等行为，将追究法律责任，后果自负
-->
<template>
	<view class="padding-bottom">
		<view class="cu-custom" :style="[{height:StatusBar + 'px'}]">
			<view class="cu-bar fixed" :style="[{paddingTop: StatusBar + 'px',height: CustomBar+'px'}]">
				<navigator v-if="CanBack" open-type="navigateBack" class="bg-black-black round margin-lr "
					style="padding: 5px 6px;"><text class="cuIcon-back "></text></navigator>
				<navigator v-else open-type="switchTab" url="/pages/home/index" class="bg-black-black round margin-lr "
					style="padding: 5px 6px;">
					<text class="cuIcon-home">首页</text>
				</navigator>
			</view>
		</view>
		<view class="product-bg margin-bottom-xs">
			<swiper :class="'screen-swiper square-dot'" indicator-dots="true" circular="true" autoplay="true"
				interval="5000" duration="500" @change="change" indicator-color="#cccccc"
				indicator-active-color="#333333">
				<swiper-item v-for="(item, index) in goodsSpu.picUrls" :key="index">
					<image :src="item" mode="aspectFill"></image>
				</swiper-item>
			</swiper>
		</view>
		<view class="padding-lr-sm">
			<view class="goods-activeBackground" :style="{'background-image': goodsSpu.activeBackground&&goodsSpu.activeBackground.picUrl?'url('+goodsSpu.activeBackground.picUrl+')':''}">
				<view class="padding-sm radius-lg">
					<view class="text-xxl">
						<text class="text-price text-scarlet text-bold">{{goodsSpu.priceDown}}</text>
						<text v-if="goodsSpu.priceDown != goodsSpu.priceUp" class="text-scarlet margin-lr-xs">-</text>
						<text v-if="goodsSpu.priceDown != goodsSpu.priceUp"
							class="text-scarlet text-bold">{{goodsSpu.priceUp}}</text>
						<text v-if="goodsSpu.marketPrice != 0"
							class="text-price text-gray text-df text-decorat margin-left-sm">{{goodsSpu.marketPrice}}</text>
					</view>
					<view class="flex align-center margin-top-sm justify-between" v-if="couponInfoList.length > 0">
						<view class="flex" @tap="showModalCoupon">
							<view class="coupon text-sm text-scarlet">{{couponInfoList[0].name}}</view>
							<view class="coupon text-sm text-scarlet margin-left-xs" v-if="couponInfoList.length > 1">
								{{couponInfoList[1].name}}</view>
						</view>
						<view @tap="showModalCoupon" class="round text-sm coupon-more"
							:class="'bg-'+theme.backgroundColor">领券</view>
					</view>
				</view>
			</view>
			<view class="bg-white padding-sm margin-top-xs radius-lg">
				<view class="text-xl text-bold">
					<text class="text-black">{{goodsSpu.name}}</text>
				</view>
				<view class="text-df padding-tb-xs">
					<text class="text-gray overflow-2">{{goodsSpu.sellPoint}}</text>
				</view>
				<view class="flex align-center text-gray justify-between margin-top-sm text-df">
					<view class="text-gray text-right">已售{{goodsSpu.saleNum?goodsSpu.saleNum:0}}</view>
					<view @tap="userCollect">
						<text :class="'cuIcon-' + (goodsSpu.collectId ? 'favorfill text-scarlet' : 'favor')"></text>
						<text  class="margin-left-xs">{{goodsSpu.collectId ? '已收藏' : '收藏'}}</text>
					</view>
					<view @tap="shareShowFun">
						<text class="cuIcon-forward"></text>
						<text class="margin-left-xs">分享</text>
					</view>
				</view>
			</view>
			<view class="bg-white radius-lg margin-top-xs text-df">
				<view class="flex padding-top-sm padding-bottom-xs">
					<view class="flex-sub">
						<view class="text-gray margin-left-sm">发货</view>
					</view>
					<view class="flex-four">
						<text class="cuIcon-location text-black"
							v-if="goodsSpu.deliveryPlace">{{goodsSpu.deliveryPlace.place}} |</text>
						<text class="text-black"
							v-if="goodsSpu.freightTemplat">运费：{{goodsSpu.freightTemplat.type == '2' ? '全国包邮' : '￥'+goodsSpu.freightTemplat.firstFreight}}</text>
					</view>
				</view>
				<view class="padding-bottom-xs" v-if="goodsSpu.pointsGiveSwitch == '1' || goodsSpu.pointsDeductSwitch == '1'">
					<view class="flex">
						<view class="flex-sub">
							<view class="text-gray margin-left-sm">优惠</view>
						</view>
						<view class="flex-four">
							<view v-if="goodsSpu.pointsGiveSwitch == '1'">
								<text class="cu-tag bg-red light sm radius">积分赠送</text>
								<text class="text-black margin-left-xs">购买可获得{{goodsSpu.pointsGiveNum}}积分</text>
							</view>
							<view class="margin-top-xs" v-if="goodsSpu.pointsDeductSwitch == '1'">
								<text class="cu-tag bg-red light sm radius">积分抵扣</text>
								<text
									class="text-black margin-left-xs">1积分可抵{{goodsSpu.pointsDeductAmount}}元，最多可抵{{goodsSpu.pointsDeductScale}}%</text>
							</view>
						</view>
					</view>
				</view>
				<view class="padding-bottom-xs" v-if="ensureList.length > 0">
					<view class="flex" @tap="showModalService">
						<view class="flex-sub">
							<view class="text-gray margin-left-sm">服务</view>
						</view>
						<view class="flex-treble">
							<text class="text-black">{{ensureList[0].name}}</text>
						</view>
						<view class="flex-sub text-gray text-right">
							<text class="cuIcon-right margin-right-sm"></text>
						</view>
					</view>
				</view>
				<view :class="'cu-modal bottom-modal ' + modalService" @tap="hideModalService"
					catchtouchmove="touchMove">
					<view class="cu-dialog" :class="modalService ? 'animation-slide-bottom' : ''" @tap.stop>
						<view class="padding-xl">
							<view class="text-lg text-center">基础服务</view>
							<view class="cu-list text-left solid-bottom">
								<view class="cu-item" v-for="(item, index) in ensureList" :key="index">
									<view class="content padding-tb-sm">
										<view><text
												class="cuIcon-roundcheckfill text-orange margin-right-xs"></text>{{item.name}}
										</view>
										<view class="text-gray " v-if="item.detail">{{item.detail}}</view>
									</view>
								</view>
							</view>
							<button class="cu-btn margin-top response lg" :class="'bg-'+theme.themeColor"
								@tap="hideModalService">确定</button>
						</view>
					</view>
				</view>
				<coupon-receive :couponInfoList="couponInfoList" :modalCoupon="modalCoupon"
					@changeModalCoupon="modalCoupon=$event" @receiveCouponChange="receiveCouponChange($event)">
				</coupon-receive>
				<view class="bg-white card-radius padding-bottom-sm" v-if="goodsSpu.specType == '1'">
					<view class="flex" @tap="showModalSku">
						<view class="flex-sub">
							<view class="text-gray margin-left-sm">选择</view>
						</view>
						<view class="flex-treble text-black">
							<view class="display-ib" v-for="(item, index) in goodsSpecData" :key="index">
								<view class="display-ib" v-if="!item.checked">{{item.value}}</view>
								<view class="display-ib" v-if="item.checked" v-for="(item2, index2) in item.leaf"
									:key="index2">
									<view class="display-ib" v-if="item.checked == item2.id">{{item2.value}}</view>
								</view>
								<view class="display-ib" v-if="goodsSpecData.length != (index+1)">,</view>
							</view>
						</view>
						<view class="flex-sub text-gray text-right">
							<text class="cuIcon-right margin-right-sm"></text>
						</view>
					</view>
				</view>
			</view>

			<view class="margin-top-xs" v-if="theme.showType!='2'">
				<shopInfo :shopInfo="shopInfo" :card="false"></shopInfo>
			</view>

			<view class="cu-bar bg-white margin-top-xs solid-bottom top-radius-lg text-df">
				<view class="flex response">
					<view class="flex-sub">
						<view class="text-black margin-left-sm">宝贝评价（{{goodsAppraises.total?goodsAppraises.total:0}}）
						</view>
					</view>
					<navigator :url="'/pages/appraises/list/index?spuId=' + id" hover-class="none"
						class="flex-sub text-df text-gray text-right margin-right-sm" v-if="goodsAppraises.total > 0">
						查看全部<text class="cuIcon-right"></text>
					</navigator>
				</view>
			</view>
			<view class="cu-list menu-avatar comment bottom-radius-lg">
				<navigator :url="'/pages/appraises/list/index?spuId=' + goodsSpu.id" hover-class="none" class="cu-item"
					v-for="(item, index) in goodsAppraises.records" :key="index">
					<view class="cu-avatar round" :style="'background-image:url(' + item.headimgUrl + ')'">
						{{!item.headimgUrl ? '头' : ''}}
					</view>
					<view class="content padding-bottom-xs margin-top-xs">
						<view class="text-black">{{item.nickName ? item.nickName : '匿名'}}
							<view class="text-gray margin-left text-sm">{{item.createTime}}</view>
						</view>
						<view class="text-gray text-sm" v-if="item.specInfo">规格：{{item.specInfo}}</view>
						<base-rade :value="item.goodsScore" size="lg"></base-rade>
						<view class="text-black text-content text-sm overflow-2">
							{{item.content ? item.content : '此人很懒没写评语'}}
						</view>
						<view class="grid col-4 grid-square flex-sub">
							<view class="bg-img margin-top-sm" v-for="(picUrl, index2) in item.picUrls" :key="index2">
								<image :src="picUrl" mode='aspectFill'></image>
							</view>
						</view>
					</view>
				</navigator>
			</view>

			<view class="cu-bar bg-white margin-top-xs radius-lg">
				<view class="content">商品信息</view>
			</view>
			<view class="bg-white">
				<jyf-parser :html="article_description"></jyf-parser>
			</view>

			<view class="cu-load bg-gray to-down">已经到底啦...</view>
		</view>

		<view class="cu-bar bg-white tabbar border shop foot" v-if="shopInfo">
			<view v-if="theme.showType!=2" class="action bg-white" open-type="navigate"
				@click="toShopHome(shopInfo.id)">
				<view class="cuIcon-shop text-red " style="font-size: 20px;"></view>
				<text class="text-red">店铺</text>
			</view>
			<navigator class="action bg-white" open-type="navigate"
				:url="'/pages/customer-service/customer-service-list/index?shopId='+shopInfo.id+'&goodsSpuId='+goodsSpu.id">
				<view class="cuIcon-comment" style="font-size: 20px;"></view>客服
			</navigator>
			<navigator class="action" open-type="switchTab" url="/pages/shopping-cart/index">
				<view class="cuIcon-cart" style="font-size: 20px;">
					<view class="cu-tag badge">{{shoppingCartCount}}</view>
				</view>购物车
			</navigator>
			<view class="btn-group ">
				<button class="cu-btn bg-orange round margin-left-sm " @tap="showModalSku"
					data-type="1">加入购物车</button>
				<button class="cu-btn round" :class="'bg-'+theme.backgroundColor" @tap="showModalSku"
					data-type="2">立即购买</button>
			</view>
		</view>
		<goods-sku :goodsSpu="goodsSpu" :cartNum="cartNum" :shopInfo="shopInfo" @numChange="cartNum = $event"
			:goodsSku="goodsSku" @changeGoodsSku="goodsSku = $event" :goodsSpecData="goodsSpecData"
			@changeSpec="goodsSpecData = $event" :modalSku="modalSku" @changeModalSku="modalSku=$event"
			:modalSkuType="modalSkuType" @operateCartEvent="operateCartEvent"></goods-sku>

		<view :class="'cu-modal ' + (goodsSpu.shelf=='0' || shopInfo.enable == '0' ? 'show' : '')">
			<view class="cu-dialog bg-white">
				<view class="cu-bar  justify-end">
					<view class="content">提示</view>
				</view>
				<view class="padding-xl">
					抱歉，该{{goodsSpu.shelf=='0' ? '商品' : shopInfo.enable == '0' ? '商品所属店铺' : ''}}已下架
				</view>
				<view class="padding">
					<navigator open-type="navigateBack" class="cu-btn margin-top response lg"
						:class="'bg-'+theme.themeColor">
						确定
					</navigator>
				</view>
			</view>

		</view>
		<!-- 分享组件 -->
		<share-component v-model="showShare" :shareParams="shareParams"></share-component>

	</view>
</template>

<script>
	/**
	 * Copyright (C) 2018-2022
	 * All rights reserved, Designed By www.joolun.com
	 * 注意：
	 * 本软件为www.joolun.com开发研制，未经购买不得使用
	 * 购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
	 * 一经发现盗用、分享等行为，将追究法律责任，后果自负
	 */

	import goodsSku from "@/components/goods-sku/index";

	const {
		base64src
	} = require("utils/base64src.js");
	const app = getApp();
	import api from 'utils/api'
	import jweixin from '@/utils/jweixin'
	import util from '@/utils/util'

	import baseRade from "components/base-rade/index";
	import couponReceive from "@/components/coupon-receive/index";
	import shopInfo from "components/shop-info/index";
	import shareComponent from "@/components/share-component/index"

	export default {
		components: {
			goodsSku,
			baseRade,
			couponReceive,
			shopInfo,
			shareComponent,
		},
		data() {
			return {
				CanBack: true,
				CustomBar: this.CustomBar,
				StatusBar: this.StatusBar,
				theme: app.globalData.theme, //全局主题变量
				shopInfo: {},
				cartNum: 1,
				goodsSpu: {
					picUrls: []
				},
				goodsSku: {},
				goodsSpecData: [],
				goodsAppraises: {},
				currents: 1,
				modalSku: false,
				modalSkuType: '',
				shoppingCartCount: 0,
				shareShow: '',
				curLocalUrl: '',
				ensureList: [],
				modalService: '',
				modalCoupon: false,
				couponInfoList: [],
				id: "",
				posterUrl: "",
				posterShow: false,
				posterConfig: "",
				article_description: "",
				showShare: false,
				shareParams: {}
			};
		},
		// 组件所在页面的生命周期函数
		mounted: function() {
			let pages = getCurrentPages()
			if (pages.length <= 1 || pages[pages.length - 1].route == 'pages/login/index') { //判断是否能返回
				this.CanBack = false
			} else {
				this.CanBack = true
			}
		},
		props: {},
		onLoad(options) {
			// 保存别人分享来的 userCode
			util.saveSharerUserCode(options);
			let id;
			if (options.scene) {
				//接受二维码中参数
				let scenes = decodeURIComponent(options.scene).split('&');
				id = scenes[0];
			} else {
				id = options.id;
			}
			this.id = id;
			app.initPage().then(res => {
				this.goodsGet(id);
				this.couponInfoPage(id);
				this.shoppingCartCountFun();
				this.goodsAppraisesPage();
				this.listEnsureBySpuId(id);
			});
		},
		onShareAppMessage: function() {
			let goodsSpu = this.goodsSpu;
			let title = goodsSpu.name;
			let imageUrl = goodsSpu.picUrls[0];

			const userInfo = uni.getStorageSync('user_info')
			let userCode = userInfo ? '&sharer_user_code=' + userInfo.userCode : ''
			let path = 'pages/goods/goods-detail/index?id=' + goodsSpu.id + userCode;
			return {
				title: title,
				path: path,
				imageUrl: imageUrl,
				success: function(res) {
					if (res.errMsg == 'shareAppMessage:ok') {
						console.log(res.errMsg);
					}
				},
				fail: function(res) { // 转发失败
				}
			};
		},
		methods: {
			goodsGet(id) {
				api.goodsGet(id).then(res => {
					this.goodsSpu = res.data;
					this.goodsSpecGet(id);
					//获取店铺信息
					this.shopInfoGet(this.goodsSpu.shopId);
					if (this.goodsSpu) {
						this.goodsSku = this.goodsSpu.specType == '0' ? this.goodsSpu.skus[0] : {}
					}
					//获取多规格商品市场价最大值
					let marketPrice = 0
					this.goodsSpu.skus.forEach((item, index) => {
						if (marketPrice < item.marketPrice) {
							marketPrice = item.marketPrice
						}
					})
					this.goodsSpu.marketPrice = marketPrice
					//WxParse.wxParse('description', 'html', goodsSpu.description, this, 0)
					setTimeout(() => {
						this.article_description = this.goodsSpu.description;
					}, 300);
				}).catch(res => {
					uni.showModal({
						title: '该商品不存在或已删除',
						showCancel: false,
						success: function(res) {
							uni.navigateBack({
								delta: 1
							});
						}
					});
				});
			},

			//跳转到商铺首页
			toShopHome(id) {
				uni.navigateTo({
					url: '/pages/shop/shop-detail/index?id=' + id
				});
			},

			//查询店铺
			shopInfoGet(shopId) {
				api.shopInfoGet(shopId).then(res => {
					this.shopInfo = res.data;
				});
			},

			goodsSpecGet(spuId) {
				api.goodsSpecGet({
					spuId: spuId
				}).then(res => {
					res.data ? res.data.map(t => {
						t.checked = ''
					}) : [];
					this.goodsSpecData = res.data;
				});
			},

			goodsAppraisesPage() {
				api.goodsAppraisesPage({
					current: 1,
					size: 1,
					descs: 'create_time',
					spuId: this.id
				}).then(res => {
					this.goodsAppraises = res.data;
				});
			},

			//查询商品可用电子券
			couponInfoPage(spuId) {
				api.couponInfoPage({
					current: 1,
					size: 50,
					descs: 'create_time',
					spuId: spuId
				}).then(res => {
					this.couponInfoList = res.data.records;
				});
			},

			receiveCouponChange(obj) { //更新单条数据
				this.couponInfoList[obj.index] = obj.item;
				this.couponInfoList.splice(); //确保页面刷新成功
			},

			//获取商品保障
			listEnsureBySpuId(spuId) {
				api.listEnsureBySpuId({
					spuId: spuId
				}).then(res => {
					this.ensureList = res.data;
				});
			},

			change: function(e) {
				this.currents = e.detail.current + 1;
			},

			showModalService() {
				this.modalService = 'show';
			},

			hideModalService() {
				this.modalService = '';
			},

			showModalCoupon() {
				this.modalCoupon = true;
			},

			hideModalCoupon() {
				this.modalCoupon = false;
			},

			showModalSku(e) {
				this.modalSku = true;
				this.modalSkuType = e.target.dataset.type ? e.target.dataset.type + '' : '';
			},

			shoppingCartCountFun() {
				api.shoppingCartCount().then(res => {
					this.shoppingCartCount = res.data; //设置TabBar购物车数量
					app.globalData.shoppingCartCount = this.shoppingCartCount + '';
				});
			},
			operateCartEvent() {
				this.shoppingCartCountFun();
			},
			//收藏
			userCollect() {
				let goodsSpu = this.goodsSpu;
				let collectId = goodsSpu.collectId;
				if (collectId) {
					api.userCollectDel(collectId).then(res => {
						uni.showToast({
							title: '已取消收藏',
							icon: 'success',
							duration: 2000
						});
						goodsSpu.collectId = null;
						this.goodsSpu = goodsSpu;
					});
				} else {
					api.userCollectAdd({
						type: '1',
						relationIds: [goodsSpu.id]
					}).then(res => {
						uni.showToast({
							title: '收藏成功',
							icon: 'success',
							duration: 2000
						});
						goodsSpu.collectId = res.data[0].id;
						this.goodsSpu = goodsSpu;
					});
				}
			},
			shareShowFun() {
				// 分享海报需要配置的参数
				let desc = '长按识别小程序码';
				let qrCode = ""; //海报配置请参考 https://github.com/jasondu/wxa-plugin-canvas
				let shareImg = this.goodsSpu.picUrls[0]; // 海报图片

				// #ifdef H5 || APP-PLUS
				desc = '长按识别二维码';
				// h5的海报分享的图片有的有跨域问题，所以统一转成base64的
				// 之所以不在组件里面转换是因为无法区分哪张image图片需要处理，一般处理主图
				shareImg = util.imgUrlToBase64(shareImg);
				// #endif
				//海报配置请参考 https://github.com/jasondu/wxa-plugin-canvas
				let posterConfig = {
					width: 750,
					height: 1280,
					backgroundColor: '#fff',
					debug: false,
					blocks: [{
						width: 690,
						height: 808,
						x: 30,
						y: 183,
						borderWidth: 2,
						borderColor: '#f0c2a0',
						borderRadius: 20
					}, {
						width: 634,
						height: 74,
						x: 59,
						y: 770,
						backgroundColor: '#fff',
						opacity: 0.5,
						zIndex: 100
					}, ],
					texts: [{
						x: 30,
						y: 113,
						baseLine: 'top',
						text: '发现一个好物，推荐给你呀',
						fontSize: 38,
						color: '#080808'
					}, {
						x: 92,
						y: 810,
						fontSize: 38,
						baseLine: 'middle',
						text: this.goodsSpu.name,
						width: 570,
						lineNum: 1,
						color: '#080808',
						zIndex: 200
					}, {
						x: 59,
						y: 895,
						baseLine: 'middle',
						text: [{
							text: '只需',
							fontSize: 28,
							color: '#ec1731'
						}, {
							text: '¥' + this.goodsSpu.priceDown,
							fontSize: 36,
							color: '#ec1731',
							marginLeft: 30
						}, ]
					}, {
						x: 522,
						y: 895,
						baseLine: 'middle',
						text: '已售' + this.goodsSpu.saleNum,
						fontSize: 28,
						color: '#929292'
					}, {
						x: 59,
						y: 945,
						baseLine: 'middle',
						text: [{
							text: this.goodsSpu.sellPoint,
							fontSize: 28,
							color: '#929292',
							width: 570,
							lineNum: 1
						}]
					}, {
						x: 360,
						y: 1065,
						baseLine: 'top',
						text: desc,
						fontSize: 38,
						color: '#080808'
					}, {
						x: 360,
						y: 1123,
						baseLine: 'top',
						text: '超值好货快来购买',
						fontSize: 28,
						color: '#929292'
					}, ],
					images: [{
						width: 634,
						height: 634,
						x: 59,
						y: 210,
						url: shareImg
					}, {
						width: 230,
						height: 230,
						x: 92,
						y: 1020,
						url: null,
						qrCodeName: 'qrCodeName', // 二维码唯一区分标识
					}, ]
				};
				let userInfo = uni.getStorageSync('user_info');
				if (userInfo && userInfo.headimgUrl) {
					//如果有头像则显示
					posterConfig.images.push({
						width: 62,
						height: 62,
						x: 30,
						y: 30,
						borderRadius: 62,
						url: userInfo.headimgUrl
					});
					posterConfig.texts.push({
						x: 113,
						y: 61,
						baseLine: 'middle',
						text: userInfo.nickName,
						fontSize: 32,
						color: '#8d8d8d'
					});
				}
				this.shareParams = {
					title: '发现一个好物，推荐给你呀',
					desc: this.goodsSpu.name,
					imgUrl: this.goodsSpu.picUrls[0],
					scene: this.goodsSpu.id,
					page: 'pages/goods/goods-detail/index',
					posterConfig: posterConfig
				}
				this.showShare = true;
			},
		}
	};
</script>
<style>
	.bg-black-black {
		background-color: rgba(0, 0, 0, 0.5);
		color: #ffffff;
	}

	.fixed {
		position: fixed;
		z-index: 99;
	}

	.product-bg {
		width: 100%;
		position: relative;
	}

	.coupon-more {
		padding: 2px 12px;
	}

	.card-radius {
		border-radius: 12rpx;
	}

	.bg-shadeTop {
		background-image: linear-gradient(rgba(0, 0, 0, 0.7), rgba(0, 0, 0, 0));
		color: #ffffff;
	}

	.product-bg swiper {
		width: 100%;
		height: calc(100vw);
		position: relative;
	}

	.product-bg .page-index {
		position: absolute;
		right: 30rpx;
		bottom: 30rpx;
	}

	.cu-bar.tabbar.shop .action {
		width: unset;
	}

	.to-down {
		margin-bottom: 100rpx
	}

	.coupon {
		border-radius: 6rpx;
		padding: 8rpx 20rpx 8rpx 20rpx;
		background-color: #fbeae7;
	}

	.goods-activeBackground {
		position: relative;
		background-color: #fff;
		border-radius: 12rpx;
		height: 160rpx;
		background-size: 100% 160rpx;
	}
</style>
